<?php

namespace app\model;

class CodeModel {

    //验证码长度
    const VERIFY_CODE_LENTH = 6;
    //验证码有效时长
    const VERIFY_CODE_EXPIRE_TIME = 6;

    //验证码缓存
    const VERIFY_CODE_MOBILE_REDIS_KEY_PREFIX = "verify:code:mobile:";

    //手机号验证码发送次数
    const VERIFY_CODE_MOBILE_MAX_NUM = 6;
    //手机号验证码每日缓存
    const VERIFY_CODE_MOBILE_MAX_NUM_REDIS_KEY_PREFIX = "code:today:mobile:";
    //IP验证码发送次数
    const VERIFY_CODE_IP_MAX_NUM = 6;
    //IP验证码发送次数
    const VERIFY_CODE_IP_MAX_NUM_REDIS_KEY_PREFIX = "code:today:ip:";

    private $redisModel;

    private $appName;


    public function __construct()
    {
        $this->redisModel = new RedisModel();

        $this->appName = config("app.app_name");
    }


    /*
    * 缓存验证码
    * */
    public function setVerifyMobileCode($mobile,$code){
        if(empty($mobile)) return false;
        $redisKey = self::VERIFY_CODE_MOBILE_REDIS_KEY_PREFIX .$mobile;
        return $this->redisModel->set($redisKey,$code,self::VERIFY_CODE_EXPIRE_TIME * 60);
    }


    /*
 * 缓存验证码
 * */
    public function getVerifyMobileCode($mobile){
        if(empty($mobile)) return false;
        $redisKey = self::VERIFY_CODE_MOBILE_REDIS_KEY_PREFIX .$mobile;
        return $this->redisModel->get($redisKey);
    }



    /*
     * 检查手机号能否发送验证码
     * */
    public function isMobileTodayCanSend($mobile){
         if(empty($mobile)) return false;
         $redisKey = self::VERIFY_CODE_MOBILE_MAX_NUM_REDIS_KEY_PREFIX .date("Ymd").$mobile;
         return $this->redisModel->get($redisKey) < self::VERIFY_CODE_MOBILE_MAX_NUM;
    }



    /*
     * 检查今天能不能发送验证码
     * */
    public function isIpTodayCanSend($ip){
        if(empty($ip)) return false;
        $redisKey = self::VERIFY_CODE_IP_MAX_NUM_REDIS_KEY_PREFIX .date("Ymd").$ip;
        return $this->redisModel->get($redisKey) < self::VERIFY_CODE_IP_MAX_NUM;
    }


    /*
     * 增加手机号的发送记录
     * */
    public function incrMobileTodaySendNum($mobile){
        if(empty($mobile)) return false;
        $redisKey = self::VERIFY_CODE_MOBILE_MAX_NUM_REDIS_KEY_PREFIX .date("Ymd").$mobile;
        return $this->redisModel->incr($redisKey);
    }


    /*
     * 增加IP的发送记录
     * */
    public function incrIpTodaySendNum($ip){
        if(empty($ip)) return false;
        $redisKey = self::VERIFY_CODE_IP_MAX_NUM_REDIS_KEY_PREFIX .date("Ymd").$ip;
        return $this->redisModel->incr($redisKey);
    }


    /*
     * 构建验证码
     * */
    public function generateCode(){
        return generateRandomNumber(self::VERIFY_CODE_LENTH);
    }



    /*
     * 构建注册验证码消息
     * */
    public function generateSendCodeMsg($code){
        return sprintf ( "【%s】 你的验证码是：%u ，有效期 %u 分钟，请不要告诉别人哦！" , $this->appName , $code , self::VERIFY_CODE_EXPIRE_TIME ) ;
    }




}